<?php

function renderPHPFile($filename, $vars = array()) {
	unset($filename, $vars);
	ob_start();
	extract(func_get_arg(1), EXTR_OVERWRITE + EXTR_PREFIX_INVALID, 'var');
	include func_get_arg(0);
	$output = ob_get_contents();
	ob_end_clean();
	return $output;
}

class nView {

	protected $stack = array();
	protected $is_ajax = null;

	protected function __construct() {

	}

	/** @return nView */
	public static function i() {
		static $instance;
		if ($instance)
			return $instance;
		else
			return $instance = new self();
	}

	public function wrapWith($template, $vars = array(), $ajax = true) {
		if ($ajax || !$this->isAjax()) {
			array_pop($this->stack);
			array_push($this->stack, array($template, $vars, $ajax));
		}
	}

	public function renderTemplate($template, $vars = array(), $ajax = true) {
		if ($ajax || !$this->isAjax()) {
			array_push($this->stack, null);
			$nContent = renderPHPFile(
				nCore::i()->dirApp() . '/' . $template . (is_string($ajax) ? $ajax : '') . '.php',
				$vars
			);
			$wrap = array_pop($this->stack);
			if (is_array($wrap)) {
				$wrap[1]['nContent'] = $nContent;
				return $this->renderTemplate($wrap[0], $wrap[1], $wrap[2]);
			} else
				return $nContent;
		}
	}

	public function isAjax() {
		if (is_bool($this->is_ajax)) return $this->is_ajax;
		return $this->is_ajax =
			array_key_exists('X-Requested-With', $_SERVER)
			&& $_SERVER['X-Requested-With'] == 'XMLHttpRequest';
	}

}